import redis

from src.utils.config import config


class RedisPool:
    def __init__(self, redis_config, config_section, decode_responses=True):
        self.config = redis_config
        self.config_section = config_section
        self.pool = None
        self.decode_responses = decode_responses
        self._config_redis()

    def _config_redis(self):
        self.host = self.config.get_config(self.config_section, 'redis_host')
        self.port = int(self.config.get_config(self.config_section, 'redis_port', 6379))
        self.db = int(self.config.get_config(self.config_section, 'redis_db', 0))
        self.password = self.config.get_config(self.config_section, 'redis_password', None)

    def get_pool(self):
        if self.pool is None:
            self.pool = redis.ConnectionPool(host=self.host, port=self.port, db=self.db, password=self.password,
                                             decode_responses=self.decode_responses)
        return self.pool

    def get_redis_conn(self):
        if self.pool is None:
            self.get_pool()
        return redis.StrictRedis(connection_pool=self.pool)


redis_pool = RedisPool(config, 'redis')
redis_conn = redis_pool.get_redis_conn()
